<template>
  <div class="purchase-order">
    <!-- 顶部操作区 -->
    <div class="top-section">
      <div class="mode-switch">
        <el-radio-group v-model="entryMode">
          <el-radio label="normal">购货单录入</el-radio>
          <el-radio label="special">购货单特殊场景录入</el-radio>
        </el-radio-group>
      </div>

      <el-form :model="form" inline class="core-form">
        <el-form-item label="*供应商">
          <el-select
            v-model="form.supplier"
            placeholder="请选择供应商"
            style="width: 160px"
          >
            <el-option label="示例供应商" value="supplier1"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="业务员">
          <el-select
            v-model="form.salesman"
            placeholder="(空)"
            style="width: 160px"
          >
            <el-option label="示例业务员" value="salesman1"></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="单据日期">
          <el-date-picker
            v-model="form.documentDate"
            type="date"
            value-format="YYYY-MM-DD"
            :default-value="new Date('2025-06-24')"
            style="width: 160px"
          />
        </el-form-item>

        <el-form-item label="供应商发货地址">
          <div class="address-wrap">
            <el-input
              v-model="form.shippingAddr"
              placeholder="请输入地址"
              style="width: 200px"
              readonly
            />
            <el-icon class="edit-icon" @click="editAddress"><Edit /></el-icon>
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="text" @click="handleUpload">
            <el-icon class="mr-2"><Upload /></el-icon>上传附件
          </el-button>
        </el-form-item>

        <el-form-item>
          <div class="doc-number">
            单据编号: {{ form.docNo }}
            <el-icon class="copy-icon" @click="copyDocNo"
              ><CopyDocument
            /></el-icon>
          </div>
        </el-form-item>
      </el-form>

      <div class="action-buttons">
        <el-button type="text">商品记录</el-button>
        <el-button type="text">拆分行</el-button>
        <el-button type="primary">保存并新增</el-button>
        <el-button type="success">保存</el-button>
        <el-button type="info">批量导入</el-button>
        <el-button type="info">选择订单</el-button>
        <el-button type="warning">审核</el-button>
      </div>
    </div>

    <!-- 商品表格区（移除所有输入框） -->
    <div class="table-container">
      <el-table
        :data="tableData"
        border
        show-summary
        :summary-method="calculateSummary"
        :header-cell-style="{ background: '#F8F9FA' }"
      >
        <el-table-column type="selection" width="50" />

        <el-table-column label="*商品" width="320">
          <template #label>
            <div class="header-info">
              <span>商品</span>
              <el-tooltip content="扫描模式已关闭" placement="top">
                <el-icon class="scan-icon"><Scan /></el-icon>
              </el-tooltip>
            </div>
          </template>
          <template #default="scope">
            <div class="product-cell">
              <span class="product-name">{{
                scope.row.productName || "未选择"
              }}</span>
              <div class="image-wrapper">
                <el-image
                  v-if="scope.row.image"
                  :src="scope.row.image"
                  style="width: 40px; height: 40px"
                  fit="cover"
                />
                <span v-else class="no-img">无图</span>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="商品图片" width="80">
          <template #default="scope">
            <div class="image-wrapper">
              <el-image
                v-if="scope.row.image"
                :src="scope.row.image"
                style="width: 40px; height: 40px"
                fit="cover"
              />
              <span v-else class="no-img">无图</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="品牌" prop="brand" width="100" />
        <el-table-column label="商品备注" prop="remark" width="150" />
        <el-table-column label="属性" prop="attribute" width="100" />
        <el-table-column label="单位" prop="unit" width="100" />
        <el-table-column label="仓库" prop="warehouse" width="120" />
        <el-table-column label="可用库存" prop="availableStock" width="100" />
        <el-table-column label="数量" prop="quantity" width="100" />
        <el-table-column label="整件散包" prop="wholePackage" width="100" />
        <el-table-column label="基本单位" prop="baseUnit" width="100" />
        <el-table-column label="基本数量" prop="baseQuantity" width="100" />
        <el-table-column label="购货单价" prop="purchasePrice" width="100" />
        <el-table-column label="赠品" width="80">
          <template #default="scope">
            <el-checkbox v-model="scope.row.isGift" size="mini" disabled />
          </template>
        </el-table-column>
        <el-table-column label="含税单价" prop="taxPrice" width="100" />
        <el-table-column
          label="折后含税单价"
          prop="discountedTaxPrice"
          width="100"
        />
        <el-table-column label="折扣率(%)" prop="discountRate" width="100" />
        <el-table-column label="折扣(折)" prop="discount" width="100" />
        <el-table-column label="折扣额" prop="discountAmount" width="100" />
        <el-table-column label="折后单价" prop="discountedPrice" width="100" />
        <el-table-column label="金额" prop="amount" width="100" />
        <el-table-column label="税率(%)" prop="taxRate" width="100" />
        <el-table-column label="税额" prop="taxAmount" width="100" />
        <el-table-column label="价税合计" prop="totalAmount" width="120" />
        <el-table-column label="采购费用" prop="purchaseCost" width="100" />
        <el-table-column label="备注" prop="note" width="150" />
        <el-table-column
          label="关联购货订单号"
          prop="relatedOrder"
          width="150"
        />
      </el-table>
    </div>

    <!-- 底部信息区 -->
    <div class="bottom-section">
      <el-form :model="form" inline class="bottom-form">
        <el-form-item label="优惠率:">
          <el-input-number
            v-model="form.discountRate"
            style="width: 100px"
            suffix="%"
            readonly
          />
        </el-form-item>
        <el-form-item label="付款优惠:">
          <el-input-number
            v-model="form.paymentDiscount"
            style="width: 100px"
            readonly
          />
        </el-form-item>
        <el-form-item label="优惠后金额:">
          <span class="read-only">{{ form.discountedAmount }}</span>
        </el-form-item>
        <el-form-item label="本次付款:">
          <el-input-number
            v-model="form.currentPayment"
            style="width: 100px"
            readonly
          />
        </el-form-item>
        <el-form-item label="结算账户:">
          <el-input
            v-model="form.settlementAccount"
            style="width: 120px"
            readonly
          />
        </el-form-item>
        <el-form-item label="本次欠款:">
          <span class="read-only">{{ form.currentDebt }}</span>
        </el-form-item>
        <el-form-item label="总欠款:">
          <el-input-number
            v-model="form.totalDebt"
            style="width: 100px"
            readonly
          />
        </el-form-item>
        <el-form-item label="采购费用:">
          <el-input-number
            v-model="form.purchaseCost"
            style="width: 100px"
            readonly
          />
        </el-form-item>
        <el-form-item label="交货方式:">
          <el-input
            v-model="form.deliveryMethod"
            style="width: 120px"
            readonly
          />
        </el-form-item>
      </el-form>

      <div class="extra-actions">
        <a href="#" class="custom-field">自定义字段</a>
        <el-button type="text" @click="viewHistory">历史单据</el-button>
        <el-button type="text" @click="viewOperationLog">操作日志</el-button>
      </div>
    </div>
  </div>
</template>

<script>
import { Edit, Upload, CopyDocument, Scan } from "@element-plus/icons-vue";

export default {
  name: "PurchaseOrder",
  components: { Edit, Upload, CopyDocument, Scan }, // 移除未使用的 Question 组件
  data() {
    return {
      entryMode: "normal",
      form: {
        supplier: "",
        salesman: "",
        documentDate: "2025-06-24",
        shippingAddr: "",
        docNo: "CG20250624001",
        discountRate: 0,
        paymentDiscount: 0,
        discountedAmount: 0,
        currentPayment: 0,
        settlementAccount: "1002 银行存款",
        currentDebt: 0,
        totalDebt: 0,
        purchaseCost: 0,
        deliveryMethod: "物流配送",
      },
      tableData: Array.from({ length: 5 }, () => ({
        productName: "",
        image: "",
        brand: "",
        remark: "",
        attribute: "",
        unit: "",
        warehouse: "主仓库",
        availableStock: 0,
        quantity: 0,
        wholePackage: "",
        baseUnit: "",
        baseQuantity: 0,
        purchasePrice: 0,
        isGift: false,
        taxPrice: 0,
        discountedTaxPrice: 0,
        discountRate: 0,
        discount: 10,
        discountAmount: 0,
        discountedPrice: 0,
        amount: 0,
        taxRate: 0,
        taxAmount: 0,
        totalAmount: 0,
        purchaseCost: 0,
        note: "",
        relatedOrder: "",
      })),
    };
  },
  computed: {
    discountedAmount() {
      const totalAmount = this.tableData.reduce(
        (acc, item) => acc + (item.totalAmount || 0),
        0
      );
      return totalAmount - this.form.paymentDiscount;
    },
    currentDebt() {
      return this.form.totalDebt - this.form.currentPayment;
    },
  },
  watch: {
    "tableData.*.taxPrice": function () {
      this.calculatePrices();
    },
    "tableData.*.discountRate": function () {
      this.calculatePrices();
    },
    "tableData.*.discount": function () {
      this.calculatePrices();
    },
    "tableData.*.taxRate": function () {
      this.calculateAmounts();
    },
    "form.paymentDiscount": {
      handler: function () {
        this.form.discountedAmount = this.discountedAmount;
        this.form.currentDebt = this.currentDebt;
      },
      immediate: true,
    },
    "form.currentPayment": {
      handler: function () {
        this.form.currentDebt = this.currentDebt;
      },
      immediate: true,
    },
  },
  methods: {
    editAddress() {
      console.log("编辑发货地址");
    },
    handleUpload() {
      console.log("触发附件上传");
    },
    copyDocNo() {
      navigator.clipboard.writeText(this.form.docNo);
      this.$message.success("单据编号已复制");
    },
    calculatePrices() {
      this.tableData.forEach((item) => {
        if (item.discountRate > 0) {
          item.discountedPrice = item.taxPrice * (1 - item.discountRate / 100);
          item.discountAmount = (item.taxPrice * item.discountRate) / 100;
          item.discount = (1 - item.discountRate / 100) * 10;
        } else if (item.discount > 0) {
          item.discountedPrice = item.taxPrice * (item.discount / 10);
          item.discountAmount = item.taxPrice * (1 - item.discount / 10);
          item.discountRate = (1 - item.discount / 10) * 100;
        } else {
          item.discountedPrice = item.taxPrice;
          item.discountAmount = 0;
          item.discount = 10;
          item.discountRate = 0;
        }
        item.discountedTaxPrice = item.discountedPrice;
      });
      this.calculateAmounts();
    },
    calculateAmounts() {
      this.tableData.forEach((item) => {
        item.amount = item.discountedPrice * item.quantity;
        item.taxAmount = item.amount * (item.taxRate / 100);
        item.totalAmount = item.amount + item.taxAmount;
      });
    },
    calculateSummary({ columns, data }) {
      const sums = [];
      columns.forEach((col, index) => {
        if (index === 0) {
          sums[index] = "合计:";
          return;
        }
        const prop = col.prop;
        if (prop === "quantity") {
          sums[index] = data.reduce((acc, cur) => acc + (cur.quantity || 0), 0);
        } else if (prop === "totalAmount") {
          sums[index] = data.reduce(
            (acc, cur) => acc + (cur.totalAmount || 0),
            0
          );
        } else if (prop === "amount") {
          sums[index] = data.reduce((acc, cur) => acc + (cur.amount || 0), 0);
        } else if (prop === "taxAmount") {
          sums[index] = data.reduce(
            (acc, cur) => acc + (cur.taxAmount || 0),
            0
          );
        } else {
          sums[index] = "";
        }
      });
      return sums;
    },
    viewHistory() {
      console.log("查看历史单据");
    },
    viewOperationLog() {
      console.log("查看操作日志");
    },
  },
  mounted() {
    this.calculatePrices();
    this.calculateAmounts();
  },
};
</script>

<style scoped>
.purchase-order {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 200px);
}

.top-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}
.mode-switch {
  margin-right: 20px;
}
.core-form {
  display: flex;
  gap: 12px;
  align-items: center;
}
.address-wrap {
  display: flex;
  align-items: center;
  gap: 4px;
}
.edit-icon {
  color: #409eff;
  cursor: pointer;
}
.doc-number {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #666;
}
.copy-icon {
  color: #409eff;
  cursor: pointer;
}
.action-buttons {
  display: flex;
  gap: 8px;
}

.table-container {
  overflow-x: auto;
  margin: 10px 0;
}
.el-table__footer-row td {
  background-color: #fff8e1 !important;
}
.header-info {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 4px;
}
.scan-icon {
  color: #999;
}
.product-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}
.image-wrapper {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f5f7fa;
  border-radius: 4px;
  overflow: hidden;
}
.no-img {
  font-size: 12px;
  color: #999;
}
.product-name {
  max-width: 180px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.bottom-section {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  margin-top: 15px;
}
.bottom-form {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}
.read-only {
  line-height: 32px;
  font-weight: 500;
  color: #333;
}
.extra-actions {
  display: flex;
  gap: 16px;
}
.custom-field {
  color: #409eff;
  text-decoration: underline;
  cursor: pointer;
}

.el-form-item__label {
  min-width: 70px;
  text-align: right;
}
.el-table th {
  text-align: center;
}
.el-input[readonly] {
  background-color: #f5f7fa;
  cursor: not-allowed;
}
</style>